#!/bin/bash
# 查看所有服务状态

set -e

# 读取当前模式
MODE=$(cat /tmp/browse-etl-mode 2>/dev/null || echo "未知")

echo "📊 服务状态检查"
echo "=================================================="
echo "🔀 当前模式: $MODE"
echo "=================================================="

# 检查Docker容器状态
echo ""
echo "🐳 Docker 容器："
docker ps -a --filter "name=browse-etl" --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}" || echo "❌ 无法连接Docker"

# 检查LocalStack
echo ""
echo "🔷 LocalStack："
if docker ps --filter "name=browse-etl-localstack" --format "{{.Status}}" | grep -q "Up"; then
    echo "  状态: ✅ 运行中"
    if curl -s http://localhost:4566/_localstack/health > /dev/null 2>&1; then
        echo "  健康检查: ✅ 正常"
        echo "  端点: http://localhost:4566"
    else
        echo "  健康检查: ⚠️  启动中"
    fi
else
    echo "  状态: ❌ 未运行"
fi

# 检查PostgreSQL
echo ""
echo "🔷 PostgreSQL："
if docker ps --filter "name=browse-etl-postgres" --format "{{.Status}}" | grep -q "Up"; then
    echo "  状态: ✅ 运行中"
    if docker exec browse-etl-postgres pg_isready -U postgres > /dev/null 2>&1; then
        echo "  健康检查: ✅ 正常"
        echo "  端点: localhost:5432"
        # 检查数据库
        DB_EXISTS=$(docker exec browse-etl-postgres psql -U postgres -tAc "SELECT 1 FROM pg_database WHERE datname='behavior_analysis'" 2>/dev/null || echo "")
        if [ "$DB_EXISTS" = "1" ]; then
            echo "  数据库: ✅ behavior_analysis 存在"
        else
            echo "  数据库: ⚠️  behavior_analysis 不存在"
        fi
    else
        echo "  健康检查: ⚠️  启动中"
    fi
else
    echo "  状态: ❌ 未运行"
fi

# 检查Event Processor
echo ""
echo "🔷 Event Processor (consumer.py)："
if docker ps --filter "name=browse-etl-event-processor" --format "{{.Status}}" | grep -q "Up"; then
    echo "  状态: ✅ 运行中"
    LAST_LOG=$(docker logs browse-etl-event-processor --tail 1 2>&1)
    if echo "$LAST_LOG" | grep -q "等待新数据\|处理完成"; then
        echo "  健康检查: ✅ 正常"
    else
        echo "  健康检查: ⚠️  可能有问题"
    fi
else
    echo "  状态: ❌ 未运行"
fi

# 检查 Flink Agents
echo ""
echo "🔷 Flink Agents："
if docker ps --filter "name=browse-etl-flink-jobmanager" --format "{{.Status}}" | grep -q "Up"; then
    echo "  JobManager: ✅ 运行中"
    echo "  Web UI: http://localhost:8081"
else
    echo "  JobManager: ❌ 未运行"
fi

if docker ps --filter "name=browse-etl-flink-taskmanager" --format "{{.Status}}" | grep -q "Up"; then
    echo "  TaskManager: ✅ 运行中"
else
    echo "  TaskManager: ❌ 未运行"
fi

# 检查本地模式 Processor
if docker ps --filter "name=browse-etl-flink-agents-processor" --format "{{.Status}}" | grep -q "Up"; then
    echo "  Agents Processor (本地模式): ✅ 运行中"
    LAST_LOG=$(docker logs browse-etl-flink-agents-processor --tail 5 2>&1)
    if echo "$LAST_LOG" | grep -q "✅\|开始轮询\|收到\|处理完成"; then
        echo "  健康检查: ✅ 正常"
    else
        echo "  健康检查: ⚠️  可能有问题"
    fi
else
    echo "  Agents Processor (本地模式): ❌ 未运行"
fi

# 检查集群模式 Processor
if docker ps --filter "name=browse-etl-flink-cluster-processor" --format "{{.Status}}" | grep -q "Up"; then
    echo "  Cluster Processor (集群模式): ✅ 运行中"
    LAST_LOG=$(docker logs browse-etl-flink-cluster-processor --tail 5 2>&1)
    if echo "$LAST_LOG" | grep -q "✅\|提交作业\|StreamExecutionEnvironment"; then
        echo "  健康检查: ✅ 正常"
    else
        echo "  健康检查: ⚠️  可能有问题"
    fi
else
    echo "  Cluster Processor (集群模式): ❌ 未运行"
fi

# 检查Lambda和API Gateway（需要LocalStack运行）
echo ""
echo "🔷 Lambda & API Gateway："
if docker ps --filter "name=browse-etl-localstack" --format "{{.Status}}" | grep -q "Up"; then
    # 检查Lambda
    LAMBDA_STATUS=$(docker exec browse-etl-localstack awslocal lambda get-function --function-name click-event-handler --query 'Configuration.State' --output text 2>/dev/null || echo "NotFound")
    if [ "$LAMBDA_STATUS" = "Active" ]; then
        echo "  Lambda: ✅ click-event-handler (Active)"
    elif [ "$LAMBDA_STATUS" = "NotFound" ]; then
        echo "  Lambda: ⚠️  未部署（运行 make deploy）"
    else
        echo "  Lambda: ⚠️  状态: $LAMBDA_STATUS"
    fi
    
    # 检查API Gateway
    API_ID=$(docker exec browse-etl-localstack awslocal apigateway get-rest-apis --query 'items[0].id' --output text 2>/dev/null || echo "")
    if [ -n "$API_ID" ] && [ "$API_ID" != "None" ]; then
        echo "  API Gateway: ✅ $API_ID"
        echo "  端点: http://localhost:4566/restapis/$API_ID/local/_user_request_/events"
    else
        echo "  API Gateway: ⚠️  未部署"
    fi
    
    # 检查Kinesis Stream
    STREAM_STATUS=$(docker exec browse-etl-localstack awslocal kinesis describe-stream --stream-name click-events-stream --query 'StreamDescription.StreamStatus' --output text 2>/dev/null || echo "NotFound")
    if [ "$STREAM_STATUS" = "ACTIVE" ]; then
        echo "  Kinesis Stream: ✅ click-events-stream (ACTIVE)"
    else
        echo "  Kinesis Stream: ⚠️  $STREAM_STATUS"
    fi
else
    echo "  ⚠️  LocalStack 未运行，无法检查"
fi

echo ""
echo "=================================================="
echo "📝 快捷命令："
case "$MODE" in
    flink-local|flink)
        echo "   切换模式: make start / make start-flink-cluster"
        echo "   重启: make restart"
        echo "   查看 Flink UI: make flink-ui"
        echo "   查看日志: make logs-flink-local"
        ;;
    flink-cluster)
        echo "   切换模式: make start / make start-flink-local"
        echo "   重启: make restart"
        echo "   查看 Flink UI: make flink-ui"
        echo "   查看日志: make logs-flink-cluster"
        ;;
    *)
        echo "   切换模式: make start-flink-local / make start-flink-cluster"
        echo "   重启: make restart"
        echo "   查看日志: make logs-event"
        ;;
esac
echo "   停止服务: make stop"
echo "   运行测试: make test"
echo "=================================================="

